import socketserver
import logging
import threading


Format = "%(threadName)s %(message)s"
logging.basicConfig(level=logging.INFO, format=Format, datefmt="%H:%M:%S")


class Myhandler(socketserver.BaseRequestHandler):
    def __init__(self, request, client_address, server):
        self.event = threading.Event()
        super().__init__(request, client_address, server)

    def setup(self):
        super().setup()
        # self.event = threading.Event()

    def handle(self):
        with self.server.lock:
            self.server.clients[self.client_address] = self.request
        super().handle()
        print("hello, I'm client: {}".format(self.request.getpeername()[1]))
        while not self.event.is_set():
            data = self.request.recv(1024)
            if data == b'quit' or data == b'':
                print("client:{} say bye~~~".format(self.request.getpeername()))
                with self.server.lock:
                    self.server.clients.pop(self.client_address)
                break
            print("message from client{}: {}".format(self.request.getpeername(), data.decode()))
            with self.server.lock:
                for msg in self.server.clients.values():
                    msg.send(('{} message: {}'.format(self.request.getpeername()[1], data.decode())).encode())

    def finish(self):
        super().finish()
        self.event.set()


def main():
    # define server address
    addr = ('127.0.0.1', 6003)
    try:
        server = socketserver.ThreadingTCPServer(addr, Myhandler)
        # print("------------", server.__class__.mro(), "---------------")
        server.lock = threading.Lock()
        server.clients = {}
    except OSError:
        newaddr = ('127.0.0.1', addr[1] + 1)
        server = socketserver.ThreadingTCPServer(newaddr, Myhandler)
    threading.Thread(target=server.serve_forever, name='accept', daemon=True).start()

    while True:
        cmd = input(">>>")
        if cmd == 'quit':
            server.server_close()
            break
        else:
            logging.info("{}".format(threading.enumerate()))
            # print(server.clients.keys())
    print("main end............")


if __name__ == '__main__':
    main()

# 多客户端这里实现的有问题, 你没有理解这个socketserver的处理流程, 你可以再回看一下视频, 再改改